package com.jww.cloud.auth.config.error;

import com.alibaba.fastjson.JSON;
import com.jww.common.core.constant.enums.ResultCodeEnum;
import com.jww.common.web.model.dto.Result;
import com.jww.common.web.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler
 * 包装失败信息到JwwOAuth2AccessDeniedHandler
 *
 * @author wanyong
 * @date 2017/12/29
 */
@Slf4j
@Component
public class JwwOAuth2AccessDeniedHandler extends OAuth2AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("未经授权，禁止访问：{}", request.getRequestURI());
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result result = ResultUtil.fail(ResultCodeEnum.UNAUTHORIZED);
        response.setStatus(ResultCodeEnum.UNAUTHORIZED.value());
        response.getWriter().append(JSON.toJSONString(result));
    }
}
